// e:\ApacheHtml\aa\student_data_system\client\js\info_query.js
import { get, put, post, del } from './api.js';

// 查询学生信息
async function queryStudent() {
    const id = document.getElementById("studentId").value;
    if (id === "") {
        alert("请输入学号！");
        return;
    }

    try {
        const data = await get(`/users/${id}`);

        if (!data.success) {
            throw new Error(data.error || "查询失败");
        }

        const user = data.data;

        // 填充表单字段
        document.getElementById("id").value = user.sid;
        document.getElementById("name").value = user.name;
        document.getElementById("birth").value = user.birth;
        document.getElementById("major").value = user.major;
        document.getElementById("credit").value = user.credits;
        document.getElementById("remark").value = user.remark || "";

        // 设置照片
        if (user.photo && user.photo !== "NULL") {
            document.getElementById("photoPreview").src = user.photo;
        } else {
            document.getElementById("photoPreview").src = "../images/周何骏.gif";
        }

        // 性别选择（0=女, 1=男）
        const genderValue = user.gender === 1 ? "男" : "女";
        document.querySelectorAll('input[name="gender"]').forEach(radio => {
            radio.checked = false;
        });
        const genderRadio = document.querySelector(`input[name="gender"][value="${genderValue}"]`);
        if (genderRadio) {
            genderRadio.checked = true;
        }

        // 查询到数据后，学号字段设为只读
        document.getElementById("id").readOnly = true;

    } catch (error) {
        alert("查询失败：" + error.message);
        // 查询失败时清空表单并允许输入新学号
        clearForm();
    }
}

// 检查学号是否已存在
async function checkStudentIdExists(sid) {
    try {
        const data = await get(`/users/${sid}`);
        return data.success; // 如果查询成功，说明学号已存在
    } catch (error) {
        return false; // 查询失败，说明学号不存在
    }
}

// 修改学生信息
async function modify() {
    const sid = document.getElementById("id").value;
    if (!sid) {
        alert("请先查询学生信息！");
        return;
    }

    // 验证必填字段
    const name = document.getElementById("name").value.trim();
    const major = document.getElementById("major").value.trim();
    const birth = document.getElementById("birth").value;
    const credits = document.getElementById("credit").value;

    if (!name || !major || !birth || !credits) {
        alert("请填写完整的学生信息！");
        return;
    }

    const genderRadio = document.querySelector('input[name="gender"]:checked');
    if (!genderRadio) {
        alert("请选择性别！");
        return;
    }

    const requestData = {
        name: name,
        major: major,
        gender: genderRadio.value === "男" ? 1 : 0,
        birth: birth,
        credits: parseInt(credits),
        remark: document.getElementById("remark").value
    };

    // 获取照片（Base64）
    const photo = document.getElementById("photoPreview").src;
    if (photo.startsWith("data:image")) {
        requestData.photo = photo;
    }

    try {
        const result = await put(`/users/${sid}`, requestData);

        if (result.success) {
            alert("修改成功！");
        } else {
            alert("修改失败：" + result.error);
        }
    } catch (error) {
        alert("网络错误：" + error.message);
    }
}

// 添加新学生
async function add() {
    // 验证必填字段
    const sid = document.getElementById("id").value.trim();
    const name = document.getElementById("name").value.trim();
    const major = document.getElementById("major").value.trim();
    const birth = document.getElementById("birth").value;
    const credits = document.getElementById("credit").value;

    if (!sid || !name || !major || !birth || !credits) {
        alert("请填写完整的学生信息！");
        return;
    }

    // 检查学号是否已存在
    const exists = await checkStudentIdExists(sid);
    if (exists) {
        alert("学号已存在，请使用其他学号！");
        return;
    }

    const genderRadio = document.querySelector('input[name="gender"]:checked');
    if (!genderRadio) {
        alert("请选择性别！");
        return;
    }

    const requestData = {
        sid: sid,
        name: name,
        major: major,
        gender: genderRadio.value === "男" ? 1 : 0,
        birth: birth,
        credits: parseInt(credits),
        remark: document.getElementById("remark").value
    };

    const photo = document.getElementById("photoPreview").src;
    if (photo.startsWith("data:image")) {
        requestData.photo = photo;
    }

    try {
        const result = await post('/users', requestData);

        if (result.success) {
            alert("添加成功！");
            // 添加成功后，学号字段设为只读
            document.getElementById("id").readOnly = true;
        } else {
            alert("添加失败：" + result.error);
        }
    } catch (error) {
        alert("网络错误：" + error.message);
    }
}

// 删除学生
async function deleteStudent() {
    if (!confirm("确定要删除该学生吗？")) return;

    const sid = document.getElementById("id").value;
    if (!sid) {
        alert("请先查询学生信息！");
        return;
    }

    try {
        const result = await del(`/users/${sid}`);

        if (result.success) {
            alert("删除成功！");
            // 清空表单
            clearForm();
        } else {
            alert("删除失败：" + result.error);
        }
    } catch (error) {
        alert("删除失败：" + error.message);
    }
}

// 清空表单
function clearForm() {
    document.getElementById("id").value = "";
    document.getElementById("name").value = "";
    document.getElementById("birth").value = "";
    document.getElementById("major").value = "";
    document.getElementById("credit").value = "";
    document.getElementById("remark").value = "";
    document.getElementById("photoPreview").src = "../images/周何骏.gif";
    document.getElementById("studentId").value = "";
    document.getElementById("fileName").textContent = "未选择任何文件";
    document.querySelectorAll('input[name="gender"]').forEach(radio => {
        radio.checked = false;
    });
    // 清空后允许输入新学号
    document.getElementById("id").readOnly = false;
}

// 退出
function exit() {
    if (window.parent !== window) {
        // 如果在iframe中，可以通知父窗口
        window.parent.postMessage('close', '*');
    } else {
        window.close();
    }
}

// 文件上传预览
function setupPhotoUpload() {
    const photoUpload = document.getElementById("photoUpload");
    const photoBtn = document.getElementById("photoBtn");
    
    if (photoUpload && photoBtn) {
        photoBtn.addEventListener("click", function() {
            photoUpload.click();
        });
        
        photoUpload.addEventListener("change", function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById("photoPreview").src = event.target.result;
                    document.getElementById("fileName").textContent = file.name;
                };
                reader.readAsDataURL(file);
            } else {
                document.getElementById("fileName").textContent = "未选择任何文件";
            }
        });
    }
}

// 绑定事件监听器
function bindEvents() {
    const queryBtn = document.getElementById("queryBtn");
    const modifyBtn = document.getElementById("modifyBtn");
    const addBtn = document.getElementById("addBtn");
    const deleteBtn = document.getElementById("deleteBtn");
    const clearBtn = document.getElementById("clearBtn");
    const exitBtn = document.getElementById("exitBtn");
    
    if (queryBtn) queryBtn.addEventListener("click", queryStudent);
    if (modifyBtn) modifyBtn.addEventListener("click", modify);
    if (addBtn) addBtn.addEventListener("click", add);
    if (deleteBtn) deleteBtn.addEventListener("click", deleteStudent);
    if (clearBtn) clearBtn.addEventListener("click", clearForm);
    if (exitBtn) exitBtn.addEventListener("click", exit);
    
    // 回车键查询
    const studentIdInput = document.getElementById("studentId");
    if (studentIdInput) {
        studentIdInput.addEventListener("keypress", function(e) {
            if (e.key === "Enter") {
                queryStudent();
            }
        });
    }
}

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    bindEvents();
    setupPhotoUpload();
    // 页面加载时不自动查询，保持表单为空
    clearForm();
});

// 导出函数供其他模块使用
export { queryStudent, modify, add, deleteStudent, exit };